/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package logic;

import entityBeans.Interaction;
import entityBeans.Specimen;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import logic.mapping.EntityToXLS;
import xlsBeans.ExportResponse;
import xlsBeans.Filter;
import xlsBeans.HideColumn;
import xlsBeans.InteractionXLS;
import xlsBeans.LineXLS;
import xlsBeans.SpecimenXLS;



/**
 *
 * @author allankv
 */
public class Export {

    public Export(){

    }
    public ExportResponse startExporting(HideColumn hide, List<Filter> filter){
        ExportResponse r = new ExportResponse();
        try {
            // Busca todos os registro de specimens
            DatabaseHandling dh = new DatabaseHandling();
            List<Specimen> spList = dh.findAllSpecimen(filter);
            List<LineXLS> lList = new ArrayList<LineXLS>();
            // Percorre lista de specimens
            for (Specimen sp : spList) {
                r.incrementTotalSpecimen();
                r.incrementTotalLines();
                LineXLS l = null;
                EntityToXLS m = new EntityToXLS();
                // Mapeia Specimen para SpecimenXML
                SpecimenXLS sp1 = m.mapping(sp);
                // Verifica se existe interacoes relacionadas com esse specimen
                if (!sp.getInteractionList().isEmpty()) {
                    for (Interaction inte : sp.getInteractionList()) {
                        r.incrementTotalInteraction();
                        r.incrementTotalSpecimen();
                        InteractionXLS intx = m.mapping(inte);
                        SpecimenXLS sp2 = m.mapping(inte.getSpecimen());
                        // se existe, percorre lista de interação, preenche a linha com sp1, inte e sp2
                        l = new LineXLS(sp1, sp2, intx);
                        lList.add(l);
                    }
                } else {
                    // se não existe interacao, preenche linha somente com sp1
                    l = new LineXLS(sp1);
                    lList.add(l);
                }
                // add linha a lista de linha
                
            }
            SpreadsheetHandling s = new SpreadsheetHandling();
            r.setUrl(s.writeSpreadsheet(lList, hide));
        } catch (ClassNotFoundException ex) {
            r.setUrl(ex.getMessage());
            Logger.getLogger(Export.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            r.setUrl(ex.getMessage());
            Logger.getLogger(Export.class.getName()).log(Level.SEVERE, null, ex);
        }
        return r;
    }

}
